package com.wlyuan.index.domain.index.repository;


import com.wlyuan.core.domain.valueobj.OrderId;
import com.wlyuan.index.domain.index.OrderIndex;
import lombok.var;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * @author yuanjie
 */
public interface OrderIndexRepository extends ElasticsearchRepository<OrderIndex, Long> {
    default OrderIndex ofId(OrderId orderId) {
        return this.findById(orderId.getId()).orElse(null);
    }

    default Map<OrderId, OrderIndex> indexes(List<OrderId> orderIds) {
        if (CollectionUtils.isEmpty(orderIds)) {
            return Collections.emptyMap();
        }
        var ids = orderIds.stream()
                .map(OrderId::getId)
                .collect(Collectors.toList());
        var indexes = this.findAllById(ids);
        return StreamSupport.stream(indexes.spliterator(), false)
                .parallel()
                .collect(Collectors.toMap(index -> new OrderId(index.getOrderId()), index -> index));
    }
}
